/*
 * @Date: 2024-08-26 19:19:01
 * @LastEditors: lyx
 * @LastEditTime: 2024-08-27 09:38:25
 * @FilePath: \zod-demo\app\todo\form.js
 * @Description: 
 */
'use client'

import { useRef } from 'react';
import toast, { Toaster } from 'react-hot-toast';
import { addTodo } from './actions';
import { TodoSchema } from "./types";

export default function Form() {

  const formRef = useRef(null);

  const clientAction = async (formData) => {
    const submitTodo = {
      content: formData.get('todo')
    }
    console.log('clientAction submitTodo', submitTodo);
    // 客户端校验
    const result = TodoSchema.safeParse(submitTodo)
    console.log('clientAction result', result);

    if (!result.success) {
      toast.error(result.error.issues[0].message)
      return;
    }

    // 提交给服务端
    const response = await addTodo(result.data)
    if (response?.error) {
      toast.error(response.error)
      return;
    }

    formRef.current?.reset()
  }

  return (
    <>
      <form action={clientAction} className="mb-2" ref={formRef} noValidate>
        <label htmlFor="todo" className="block text-sm font-medium leading-6 text-gray-900">
          待办事项:
        </label>
        <input
          id="todo"
          name="todo"
          type="text"
          required
          className="block w-full rounded-md border-0 p-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 mb-2"
        />
        <button
          type="submit"
          className="flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"
        >
          添加
        </button>
      </form>
      <Toaster />
    </>

  );
}
